<?

include_once "messages.php";

if (isset($_POST["username"])) {
	if ($session->logUserIn(quote_smart($_POST["username"]), quote_smart($_POST["userpwd"]))) echo "{ good: 1, user: ".$session->user.", user_name: '".$session->getUserName()."' }";
}
if (isset($_GET["logout"])) {
	$session->logout();
	echo "logedout!";
}

if (isset($_POST["newusername"]) and ($_POST["newuserpwd1"] == $_POST["newuserpwd2"])) {
	$name = quote_smart($_POST["newusername"]);
	$pwd = quote_smart($_POST["newuserpwd1"]);
	$email = quote_smart($_POST["newusername"]);
	if ($users->newUser($name, $pwd, $email)) {
		$u = $users->getUserByName($name);
		if (isset($_POST["public_key"]))
			$users->setUserAttribute($u, "public_key", quote_smart($_POST["public_key"]));
		if (isset($_POST["private_key"]))
			$users->setUserAttribute($u, "private_key", quote_smart($_POST["private_key"]));
		die("registered:".$users->getUserAttribute($u, "private_key","no key!"));
	}
}

if (isset($_GET["get_my_key"])) {
	echo $session->getUserAttribute("private_key","no key!");
}
if (isset($_GET["get_key"])) {
	$u = $users->getUserByName(quote_smart($_POST["email"]));
	if ($u) {
		echo $users->getUserAttribute($u, "public_key","no key!");
	} else {
		
	}
}
if (isset($_GET["store_my_key"])) {
		if (isset($_POST["public_key"]))
			$session->setUserAttribute("public_key", quote_smart($_POST["public_key"]));
		if (isset($_POST["private_key"]))
			$session->setUserAttribute("private_key", quote_smart($_POST["private_key"]));
		echo "stored";
}
if (isset($_GET["store"])) {
		$session->setUserAttribute(quote_smart($_POST["name"]), quote_smart($_POST["value"]));
		echo "stored";
}
if (isset($_GET["get"])) {
		$session->getUserAttribute(quote_smart($_POST["name"]));
		echo "stored";
}

if (isset($_GET["what"])) {
	if ($session->loged_in) echo "{ good: 1, user: ".$session->user.", user_name: '".$users->getUserName($session->user)."' }";
}



if (isset($_GET["send"])) {
	$db->dbg = 1;
	$to = quote_smart($_POST["to"]);
	$from = quote_smart($_POST["from"]);
	$title = quote_smart($_POST["title"]);
	$text = quote_smart($_POST["text"]);
	echo $messages->newMessage($to, $from, $title, $text, "Web/User:".$users->getUserName($session->user));
}
if (isset($_GET["recieve"])) {
	$since = quote_smart($_POST["since"]);
	$limit = quote_smart($_POST["limit"]);
	echo json_encode($messages->getMyMessages($limit, $since));
}
if (isset($_GET["check_users"])) {
	$email = quote_smart($_POST["email"]);
	$us = $users->getAllUsersByEmail($email);
	$result = array();
	if ($us)
	foreach ($us as $u) {
		$result[] = $u["email"];
	}
	echo json_encode($result);
}
?>